<?php
header('Content-Type: application/json');
include('MysqliDb.php');
include('config.php');


$db = new MysqliDb ($host, $username, $password, $databaseName);
$type = $_GET['type'];

$name = $_POST['name'];
$key = $_POST['key'];

switch ($type) {
    case 1:
	//注册
        $key = $_POST['key'];
		$password = $_POST['password'];
        $db->where ("name", $name);
        $user = $db->getOne ("account");
        // echo $user['password'];
        // echo $db -> count;
        if($db -> count > 0){
        	$res['code'] = -1;
        	$res['msg'] = '用户存在:'.$name;
        }else{
        	// echo "不存在的用户".$name;
        	// 插入
        	$data = Array ("name" => $name,
        	               "password" => $password,
        	               "key" => $key
        	);
        	$id = $db->insert ("account", $data);
        	if($id)
        		$res['code'] = 0;
        	    $res['msg'] = "user was created. Id=" . $id;
        }
        
        break;
    case 2:
	// 登录
        $db->where ("name", $name);
		$password = $_POST['password'];
        $user = $db->getOne ("account");
        // echo $user['password'];
        // echo $db -> count;
        if($db -> count > 0){
        	if($password == $user['password']){
        		$res['code'] = 0;
        		$res['msg'] = "账号密码正确";
        	}else{
        		$res['code'] = -1;
        		$res['msg'] = "密码错误";
        	}
        }else{
        	$res['code'] = -1;
        	$res['msg'] = "不存在的用户";
        }
        
        break;
    case 3:
		// name绑定key，无则插入，有则更新
		$data = Array ("name" => $name,
					   "key" => $key
		);
        $db->where ("name", $name);
        $user = $db->getOne ("account");
        if($db -> count > 0){
        	// 用户存在
			if ($db->update ('account', $data))
			    $res['code'] = 0;
				$res['msg'] = $db->count . ' records were updated';
			else
			    $res['code'] = -1;
				$res['msg'] = 'update failed: ' . $db->getLastError();
        }else{
        	// echo "不存在的用户".$name;
        	// 插入
        	
        	$id = $db->insert ("account", $data);
        	if($id)
        		$res['code'] = 0;
        	    $res['msg'] = "user was created. Id=" . $id;
        }
        break;
    case 4:
        echo "今天是星期四";
        break;
}

echo json_encode($res , JSON_UNESCAPED_UNICODE);


$db -> close;